package com.test.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

@Slf4j
public class FileUtil {

    private FileUtil() {
    }

    /**
     * 保存文件
     *
     * @param file       文件
     * @param folderPath 文件目录
     * @param fileName   文件名称（xxx.jpg）
     */
    public static void saveFile(MultipartFile file, String folderPath, String fileName) {
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(folderPath + fileName))) {
            out.write(file.getBytes());
            out.flush();
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new RuntimeException("上传文件失败");
        }
    }



    /**
     * 保存文件
     *
     * @param srcPath    源文件路径
     * @param folderPath 目标文件目录
     * @param fileName   目标文件名称（xxx.jpg）
     */
    public static void saveFile(String srcPath, String folderPath, String fileName) {
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String newFilePath = folderPath + fileName;
        File newFile = new File(newFilePath);
        if (newFile.exists()) {
            //文件已存在
            return;
        }

        try (InputStream fis = new FileInputStream(srcPath);
             BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newFilePath))) {

            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("下载文件失败", e);
            throw new RuntimeException("下载文件失败");
        }
    }
}
